// 二级弹窗从PopupPanel派生
// moveArea点中可以移动，点击panel会自动切换到最上层

class PopupPanel extends eui.Panel {
	static eventOK = 'OK';

	static eventCancel = 'Cancel';

	getMouseHit(): egret.DisplayObject {
		const [mx, my] = MainWindow.ins().getMousePos();
		return this.$hitTest(mx, my);
	}

	popupBy: string;

	isShow: boolean;

	getGroup(): string {
		return '';
	}

	override async close(delay = 0): Promise<void> {
		if (!this.stage) {
			return;
		}
		if (delay > 0) {
			await waitMs(delay);
		}
		this.onClose();
	}

	toggle(): void {
		if (this.stage) {
			this.close();
			return;
		}
		this.show();
	}

	show(): void {
		this.isShow = true;
		MainWindow.ins().popup.popup(this, this.isWindowEffect() ? 'popUp' : '');
		this.onShow(true);
	}

	getOKData() {
		return null;
	}

	onOK() {
		this.dispatchEventWith(PopupPanel.eventOK, false, this.getOKData());
		this.onClose();
	}

	onCancel() {
		this.dispatchEventWith(PopupPanel.eventCancel, false);
		this.onClose();
	}

	onEsc(): void {
		this.onClose();
	}

	onShow(_visible: boolean): void {}

	setRightClose(): void {
		this.addEventListener(MainRightClick.rightDownEvent, this.onRightClose, this);
	}

	// 点中区域之外就close!
	outsideClose = false;

	registTouchOutside(): void {
		MainWindow.ins().addEventListener(
			egret.TouchEvent.TOUCH_BEGIN,
			this.onTouchBeginMain,
			this,
		);
	}

	setClickoutsideClose(): void {
		this.outsideClose = true;
		if (this.$stage) {
			this.registTouchOutside();
		}
	}

	override $onAddToStage(stage: egret.Stage, nestLevel: number): void {
		super.$onAddToStage(stage, nestLevel);
		if (this.outsideClose) {
			this.registTouchOutside();
		}
	}

	private onTouchBeginMain(e: egret.TouchEvent): void {
		const { target } = e;
		if (isSelfOrParent(target, this)) {
			return;
		}
		this.onClose();
	}

	override $onRemoveFromStage(): void {
		super.$onRemoveFromStage();
		if (this.outsideClose) {
			MainWindow.ins().removeEventListener(
				egret.TouchEvent.TOUCH_BEGIN,
				this.onTouchBeginMain,
				this,
			);
		}
	}

	onRightClose(): void {
		this.onClose();
	}

	async onClose(): Promise<void> {
		this.isShow = false;
		if (this.isWindowEffect()) {
			await asyncSetEffectUI(this, 'popDown', 100);
		}
		this.onShow(false);
		const parent: DockWindowParent = this.parent as any;
		if (parent.closeChild) {
			parent.closeChild(this);
		} else {
			this.parent.removeChild(this);
		}
	}
	// clearWhenLostFocus = false;

	btnClose: egret.DisplayObject;

	protected override childrenCreated(): void {
		super.childrenCreated();
		if (this.btnClose) {
			this.btnClose.addEventListener('touchTap', this.onClose, this);
		}
	}

	isWindowEffect(): boolean {
		return false;
	}

	bgDark: eui.Image;

	// 设置窗口样式的全屏ui点击bgDark自动关闭界面
	setBgClickClose(): void {
		if (this.bgDark) {
			this.bgDark.addEventListener('touchTap', this.close, this);
		}
	}
}
